package com.budwk.app.sqfw.services.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.popo.service.PopoInterfaceService;
import com.budwk.app.sqfw.dto.SqfwServiceRecordUpdateDTO;
import com.budwk.app.sqfw.dto.TransferServiceRecordDTO;
import com.budwk.app.sqfw.models.*;
import com.budwk.app.sqfw.services.*;
import com.budwk.app.sqfw.vo.SqfwWorkOrderVO;
import com.budwk.app.sqfw.vo.UserServiceOrderVO;
import com.budwk.app.sqfw.vo.WorkOrderWithServiceRecordVO;
import com.budwk.app.sys.models.Sys_dict;
import com.budwk.app.sys.models.Sys_unit;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysDictService;
import com.budwk.app.sys.services.SysUnitService;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.AudioToTextUtils;
import com.budwk.starter.common.page.Pagination;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.database.service.BaseServiceImpl;
import com.budwk.starter.security.utils.SecurityUtil;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.pager.Pager;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@IocBean(args = {"refer:dao"})
public class SqfwServicerecordServiceImpl extends BaseServiceImpl<Sqfw_servicerecord> implements SqfwServicerecordService {
    public SqfwServicerecordServiceImpl(Dao dao) {
        super(dao);
    }

    @Inject
    private SqfwWorkorderService sqfwWorkorderService;

    @Inject
    private PopoInterfaceService popoInterfaceService;

    @Inject
    private SqfwPoUserService poUserService;

    @Inject
    private SysUserService sysUserService;

    @Inject
    private SysUnitService sysUnitService;

    @Inject
    private SysDictService sysDictService;

    @Inject
    private SqfwCopyrecordService sqfwCopyrecordService;

    @Inject
    private SqfwCompleteflowService sqfwCompleteflowService;

    @Override
    public List<UserServiceOrderVO> listByServiceOrderIdList(List<String> serviceOrderIdList) {

        Set<String> serviceOrderIdSet = Sets.newHashSet(serviceOrderIdList);

        if (serviceOrderIdSet.size() == 0) return new ArrayList<>();
        List<Sqfw_servicerecord> serviceOrderList = query(
                Cnd.where("id", "in", serviceOrderIdSet)
                        .and("delflag", "=", false)
                        .orderBy("createdat", "desc"));

        List<UserServiceOrderVO> resultList = new ArrayList<>();

        // 使用for循环进行处理了，因为后面如果通话记录很多的情况使用in的方式可能会报错
        for (Sqfw_servicerecord serviceRecord : serviceOrderList) {

            UserServiceOrderVO resultVO = new UserServiceOrderVO();
            BeanUtil.copyProperties(serviceRecord, resultVO);

            // 根据sqfw_id 和 from_userid 查询相应的工单信息
            List<Sqfw_workorder> workOrderList = sqfwWorkorderService.query(Cnd.where("sqfw_id", "=", serviceRecord.getId())
                    .and("from_user_id", "=", serviceRecord.getCreatedBy()));
            resultVO.setUserWorkOrderList(sqfwWorkorderService.getVO(workOrderList));

            // 根据sqfw_id 和 user_id 查询该语音记录所对应的工单信息
            List<Sqfw_workorder> curServiceOrderWorkOrderList = sqfwWorkorderService.query(Cnd.where("sqfw_id", "=", serviceRecord.getId())
                    .and("user_id", "=", serviceRecord.getCreatedBy()));
            List<SqfwWorkOrderVO> curUserVOList = sqfwWorkorderService.getVO(curServiceOrderWorkOrderList);
            if (curUserVOList.size() > 0) resultVO.setUserWorkOrder(curUserVOList.get(0));

            resultList.add(resultVO);
        }
        return resultList;
    }


    /**
     * 删除服务记录
     *
     * @param serviceOrderId 服务记录
     * @return 删除的条数
     */
    @Override
    public Integer deleteServiceOrderLogic(String serviceOrderId) {

        // 将泡泡的消息撤回
        // withdrawPopoMessage(serviceOrderId);

        // 更新工单记录的删除标志
        sqfwWorkorderService.update(Chain.make("delflag", true), Cnd.where("sqfw_id", "=", serviceOrderId));

        // 删除该服务记录对应的抄送记录
        List<Sqfw_copyRecord> sqfwCopyRecordList = sqfwCopyrecordService.query(Cnd.where("sqfw_id", "=", serviceOrderId));
        if (sqfwCopyRecordList.size() > 0) {
            List<String> copyRecordIdList = sqfwCopyRecordList.stream().map(Sqfw_copyRecord::getId).collect(Collectors.toList());
            sqfwCopyrecordService.delete(copyRecordIdList);
        }

        // 更新服务记录的删除标志
        return update(Chain.make("delflag", true), Cnd.where("id", "=", serviceOrderId));
    }

    public Integer withdrawPopoMessage(String serviceOrderId) {
        // 拿到该服务记录对应的工单以及转发出去的工单信息
        List<Sqfw_workorder> workOrderList = sqfwWorkorderService.query(Cnd.where("sqfw_id", "=", serviceOrderId).and("delflag", "=", false));

        // 找到服务记录对应的工单 以及转发出去的工单
        Sqfw_workorder userWorkOrder = null;
        List<Sqfw_workorder> otherUserWorkOrderList = Lists.newArrayList();

        for (Sqfw_workorder queryWorkOrder : workOrderList) {
            if (queryWorkOrder.getCreatedBy().equals(queryWorkOrder.getUser_id())) {
                userWorkOrder = queryWorkOrder;
            } else {
                otherUserWorkOrderList.add(queryWorkOrder);
            }
        }

        // 根据系统用户找到对应的泡泡用户
        if (userWorkOrder == null) return 0;
        Set<String> sysUserIdSet = Sets.newHashSet(userWorkOrder.getUser_id());
        sysUserIdSet.addAll(otherUserWorkOrderList.stream().map(Sqfw_workorder::getUser_id).collect(Collectors.toSet()));
        List<Sqfw_po_user> poUserList = poUserService.query(Cnd.where("sys_userid", "in", sysUserIdSet));
        Map<String, Sqfw_po_user> poUserMap = poUserList.stream().collect(Collectors.toMap(Sqfw_po_user::getSys_userid, item -> item));

        // 然后查询出这些工单用户所对应的
        String loginPopUid = poUserMap.get(userWorkOrder.getUser_id()).getPo_userid();
        if (StringUtils.isBlank(loginPopUid)) return 0;

        int withdrawCount = 0;
        for (Sqfw_workorder otherUserWorkOrder : otherUserWorkOrderList) {
            String popoUid = poUserMap.get(otherUserWorkOrder.getUser_id()).getPo_userid();
            if (StringUtils.isBlank(popoUid)) continue;

            String popoMid = otherUserWorkOrder.getPopoMid();
            if (StringUtils.isBlank(popoMid)) continue;
            Integer revokeCount = popoInterfaceService.revokeMessage(loginPopUid, popoUid, popoMid);
            if (revokeCount > 0) withdrawCount++;
        }
        return withdrawCount;
    }

    @Override
    public Pagination listServiceRecord(Sqfw_servicerecord bean, int pageNo, int pageSize, boolean isAdmin, String userId) {

        String selectStr = " select ";
        String columName = " *,work_order.user_id workorder_user_id,record.createdat createdAt ,record.createdby createdby,record.id id,work_order.id workOrderId";
        String fromTable = " from shequ.sqfw_servicerecord record LEFT JOIN shequ.sqfw_workorder work_order ON work_order.sqfw_id = record.id where record.delflag = false ";
        String condition = "  ";
        String orderStr = " ORDER BY record.createdat desc ";

        condition = generateCondition(bean, isAdmin, userId);

        String sqlStr = selectStr + columName + fromTable + condition + orderStr;
        Sql sqlExecute = Sqls.create(sqlStr);
        Pager pager = dao().createPager(pageNo, pageSize);
        sqlExecute.setPager(pager);
        List<JSONObject> list = getList(sqlExecute);

        List<WorkOrderWithServiceRecordVO> resultList = Lists.newArrayList();
        for (JSONObject jsonObject : list) {
            WorkOrderWithServiceRecordVO vo = JSONObject.parseObject(JSONObject.toJSONString(jsonObject), WorkOrderWithServiceRecordVO.class);
            resultList.add(vo);
        }

        for (WorkOrderWithServiceRecordVO vo : resultList) {
            String serviceRecordId = vo.getSqfw_id();
            String createdBy = vo.getCreatedby();
            List<Sqfw_workorder> workOrderList = sqfwWorkorderService.queryBySqfwIdAndFromUserId(serviceRecordId, createdBy);
            Set<String> userIdSet = workOrderList.stream().map(Sqfw_workorder::getUser_id).collect(Collectors.toSet());
            List<Sys_user> userList = sysUserService.getUserByIds(userIdSet);

            List<String> userNameList = new ArrayList<>();
            List<String> userPhoneList = new ArrayList<>();
            for (Sys_user sys_user : userList) {
                userNameList.add(sys_user.getUsername());
                userPhoneList.add(sys_user.getMobile());
            }

            if (userNameList.size() > 0) vo.setService_name(Joiner.on(",").join(userNameList));
            if (userPhoneList.size() > 0) vo.setService_phone(Joiner.on(",").join(userPhoneList));

        }

        Sql countSqlExecute = Sqls.create(selectStr + " count(1) total_count" + fromTable + condition);
        countSqlExecute.setCallback(((connection, resultSet, sql) -> {
            int totalCount = 0;
            while (resultSet.next()) {
                totalCount = resultSet.getInt("total_count");
            }
            return totalCount;
        }));
        dao().execute(countSqlExecute);
        int totalCount = countSqlExecute.getInt();


        Pagination pagination = new Pagination();
        pagination.setTotalCount(totalCount);
        pagination.setPageNo(pageNo);
        pagination.setPageSize(pageSize);
        pagination.setList(resultList);
        return pagination;
    }

    @Override
    public Pagination listServiceRecordNew(Sqfw_servicerecord bean, int pageNo, int pageSize, Set<String> roleSet, String userId) {
        Cnd cnd = Cnd.NEW();

        boolean superAdminFlag = false;
        boolean adminFlag = false;

        if (roleSet.contains("superadmin") || roleSet.contains("sysadmin")) superAdminFlag = true;
        if (roleSet.contains("admin")) adminFlag = true;

        if (!superAdminFlag && !adminFlag) {
            Sys_user sysUser = sysUserService.fetch(userId);
            SqlExpressionGroup e1 = Cnd.exps("customer_phone", "=", sysUser.getLoginname());
            SqlExpressionGroup e2 = Cnd.exps("service_phone", "like", "%" + sysUser.getLoginname() + "%");
            cnd.and(e1.or(e2));
        }

        if (!superAdminFlag && adminFlag) {
            // 如果只是普通的管理员 首先查出这个公司中所有的员工
            Sys_user sysUser = sysUserService.fetch(userId);
            String unitId = sysUser.getUnitId();
            List<Sys_user> userList = sysUserService.query(Cnd.where("unitid", "=", unitId));
            Set<String> userPhoneSet = userList.stream().map(Sys_user::getLoginname).collect(Collectors.toSet());
            SqlExpressionGroup e = Cnd.exps("customer_phone", "like", "%" + sysUser.getLoginname() + "%");
            for (String userPhone : userPhoneSet) {
                SqlExpressionGroup e1 = Cnd.exps("customer_phone", "like", "%" + userPhone + "%");
                e.or(e1);
            }
            cnd.and(e);
        }

        if (bean.getCustomer_name() != null && Strings.isNotBlank(bean.getCustomer_name().toString())) {
            cnd.and("customer_name", "like", "%" + bean.getCustomer_name() + "%");
        }

        if (bean.getDuration() != null && Strings.isNotBlank(bean.getDuration().toString())) {
            cnd.and("duration", ">=", bean.getDuration());
        }

        if (bean.getCustomer_phone() != null && Strings.isNotBlank(bean.getCustomer_phone().toString())) {
            cnd.and("customer_phone", "like", "%" + bean.getCustomer_phone() + "%");
        }

        if (bean.getCustomer_address() != null && Strings.isNotBlank(bean.getCustomer_address().toString())) {
            cnd.and("customer_address", "like", "%" + bean.getCustomer_address() + "%");
        }

        if (bean.getRecording_file() != null && Strings.isNotBlank(bean.getRecording_file().toString())) {
            cnd.and("recording_file", "like", "%" + bean.getRecording_file() + "%");
        }

        if (bean.getRecording_text() != null && Strings.isNotBlank(bean.getRecording_text().toString())) {
            cnd.and("recording_text", "like", "%" + bean.getRecording_text() + "%");
        }

        if (bean.getType() != null && Strings.isNotBlank(bean.getType().toString())) {
            cnd.and("type", "=", bean.getType());
        }

        String timeFormat = "yyyy-MM-dd HH:mm:ss";

        if (bean.getConnect_time() != null && Strings.isNotBlank(bean.getConnect_time().toString())) {
            DateTime endTime = DateUtil.endOfDay(bean.getConnect_time());
            String startTimeStr = DateUtil.format(bean.getConnect_time(), timeFormat);
            String endTimeStr = DateUtil.format(endTime, timeFormat);
            cnd.and("connect_time", "between", new Object[]{startTimeStr, endTimeStr});
        }

        if (bean.getEnd_time() != null && Strings.isNotBlank(bean.getEnd_time().toString())) {
            DateTime endTime = DateUtil.endOfDay(bean.getEnd_time());
            String startTimeStr = DateUtil.format(bean.getEnd_time(), timeFormat);
            String endTimeStr = DateUtil.format(endTime, timeFormat);
            cnd.and("connect_time", "between", new Object[]{startTimeStr, endTimeStr});
        }

        if (bean.getCustomer_need() != null && Strings.isNotBlank(bean.getCustomer_need().toString())) {
            cnd.and("customer_need", "like", "%" + bean.getCustomer_need() + "%");
        }

        if (bean.getService_name() != null && Strings.isNotBlank(bean.getService_name().toString())) {
            cnd.and("service_name", "like", "%" + bean.getService_name() + "%");
        }

        if (bean.getService_phone() != null && Strings.isNotBlank(bean.getService_phone().toString())) {
            cnd.and("service_phone", "like", "%" + bean.getService_phone() + "%");
        }

        if (bean.getReceive_time() != null && Strings.isNotBlank(bean.getReceive_time().toString())) {
            DateTime endTime = DateUtil.endOfDay(bean.getReceive_time());
            String startTimeStr = DateUtil.format(bean.getReceive_time(), timeFormat);
            String endTimeStr = DateUtil.format(endTime, timeFormat);
            cnd.and("receive_time", "between", new Object[]{startTimeStr, endTimeStr});
        }

        if (bean.getFinish_time() != null && Strings.isNotBlank(bean.getFinish_time().toString())) {
            DateTime endTime = DateUtil.endOfDay(bean.getFinish_time());
            String startTimeStr = DateUtil.format(bean.getReceive_time(), timeFormat);
            String endTimeStr = DateUtil.format(endTime, timeFormat);
            cnd.and("finish_time", "between", new Object[]{startTimeStr, endTimeStr});
        }

        if (bean.getHandle_result() != null && Strings.isNotBlank(bean.getHandle_result().toString())) {
            cnd.and("handle_result", "=", "%" + bean.getHandle_result() + "%");
        }

        if (bean.getHandle_detail() != null && Strings.isNotBlank(bean.getHandle_detail().toString())) {
            cnd.and("handle_detail", "like", "%" + bean.getHandle_detail() + "%");
        }

        if (bean.getCopyPhone() != null && Strings.isNotBlank(bean.getCopyPhone().toString())) {
            cnd.and("copy_phone", "like", "%" + bean.getCopyPhone() + "%");
        }

        if (bean.getCopyName() != null && Strings.isNotBlank(bean.getCopyName().toString())) {
            cnd.and("copy_name", "like", "%" + bean.getCopyName() + "%");
        }

        cnd.and("delflag", "=", false);
        cnd.orderBy("createdat", "desc");

        Pagination pagination = listPage(pageNo, pageSize, cnd);
        List<Sqfw_servicerecord> serviceRecordList = pagination.getList(Sqfw_servicerecord.class);

        List<WorkOrderWithServiceRecordVO> resultList = Lists.newArrayList();
        for (Sqfw_servicerecord serviceRecord : serviceRecordList) {

            // 查询对应的工单信息
            Sqfw_workorder workOrder = null;
            List<Sqfw_workorder> workOrderList = sqfwWorkorderService.query(Cnd.where("sqfw_id", "=", serviceRecord.getId())
                    .and("user_id", "=", serviceRecord.getCreatedBy()));
            if (workOrderList.size() == 1) {
                workOrder = workOrderList.get(0);
            }

            WorkOrderWithServiceRecordVO vo = new WorkOrderWithServiceRecordVO();
            BeanUtil.copyProperties(serviceRecord, vo);
            vo.setComplete_time(serviceRecord.getFinish_time());
            vo.setWk_status(serviceRecord.getFinishStatus());
            vo.setCopy_name(serviceRecord.getCopyName());
            vo.setCopy_phone(serviceRecord.getCopyPhone());

            // wzy 2023-15-03 重新修改已完成 未完成相关代码
            // 查询该服务记录未删除的工单记录
            List<Sqfw_workorder> workOrderOfRecordList = sqfwWorkorderService.query(Cnd.where("sqfw_id", "=", serviceRecord.getId())
                    .and("delflag", "=", false));
            int workOrderCompleteCount = 0;
            int workOrderNotCompleteCount = 0;
            for (Sqfw_workorder workOrderOfRecord : workOrderOfRecordList) {
                String wk_status = workOrderOfRecord.getWk_status();
                if (StringUtils.isNotBlank(wk_status) && wk_status.equals("complete")) workOrderCompleteCount++;
                else workOrderNotCompleteCount++;
            }
            String completeMsg = StrFormatter.format("完成{}人，未完成{}人", workOrderCompleteCount, workOrderNotCompleteCount);
            vo.setHandle_result(completeMsg);

            if (workOrder != null) {
                vo.setWk_status(workOrder.getWk_status());
            }
            resultList.add(vo);
        }

        pagination.setList(resultList);
        return pagination;
    }

    @Override
    public List<String> listAllServiceOrderType(String unitId) {
        List<String> resultList = Lists.newArrayList();

        if (StringUtils.isBlank(unitId)) return resultList;

        Sys_unit unit = sysUnitService.fetch(unitId);
        if (unit == null) return resultList;

        String serviceOrderTypeDictSuffix = "_service_order_type";
        String serviceOrderTypeDictCode = "common" + serviceOrderTypeDictSuffix;
        List<Sys_dict> commonDickList = sysDictService.getSubListByCode(serviceOrderTypeDictCode);

        String unitCode = unit.getUnitcode();
        if (StringUtils.isNotBlank(unitCode)) {
            serviceOrderTypeDictCode = unitCode + serviceOrderTypeDictSuffix;
            List<Sys_dict> dictList = sysDictService.getSubListByCode(serviceOrderTypeDictCode);
            commonDickList.addAll(dictList);
        }
        return commonDickList.stream().map(Sys_dict::getName).collect(Collectors.toList());
    }

    @Override
    public Result<?> getTask(String type) {
        String userId = SecurityUtil.getUserId();
        Sys_user user = sysUserService.getUserById(userId);
        Cnd cnd = Cnd.NEW();
        cnd.and(Sqfw_servicerecord::getCreatedBy, "=", userId);
        cnd.and(Sqfw_servicerecord::getType, "=", type);
        cnd.and(Sqfw_servicerecord::getAutoCreateTask, "=", 1);
        cnd.desc(Sqfw_servicerecord::getCreatedAt);

        Sqfw_servicerecord serviceRecord = super.fetch(cnd);

        // 如果没有任务则新增一条任务
        if (serviceRecord == null) {
            serviceRecord = new Sqfw_servicerecord();
            serviceRecord.setProvince(user.getProvince());
            serviceRecord.setCity(user.getCity());
            serviceRecord.setDistrict(user.getDistrict());
            serviceRecord.setCounty(user.getCounty());
            serviceRecord.setCommunity(user.getCommunity());
            serviceRecord.setCompanyName(user.getUnitName());
            serviceRecord.setCustomer_need(type + " 【" + DateUtil.format(new Date(), "MM-dd") +"】");
            serviceRecord.setAutoCreateTask(1);
            serviceRecord.setType(type);
            serviceRecord.setCustomer_name(user.getUsername());
            serviceRecord.setCustomer_phone(user.getMobile());
            serviceRecord.setService_name(user.getUsername());
            serviceRecord.setService_phone(user.getMobile());
            serviceRecord.setUser_id(userId);
            serviceRecord.setCreatedBy(userId);
            serviceRecord.setCreatedAt(System.currentTimeMillis());
            serviceRecord = super.insert(serviceRecord);
            // 新增工单
            Sqfw_workorder workOrder = new Sqfw_workorder();
            workOrder.setSqfw_id(serviceRecord.getId());
            workOrder.setUser_name(user.getUsername());
            workOrder.setWk_grade("0");
            workOrder.setWk_priority("take_time_complete");
            workOrder.setUser_id(serviceRecord.getCreatedBy());
            workOrder.setCreateDate(new Date());
            workOrder.setUpdatedAt(new Date());
            workOrder.setCreatedBy(serviceRecord.getCreatedBy());
            // wzy 2023-5-25 服务记录生成工单的时候不主动完成对应工单
            workOrder.setWk_status("new");
            // workOrder.setComplete_time(new Date());
            workOrder.setDelflag(false);
            workOrder.setServiceType(serviceRecord.getType());
            sqfwWorkorderService.insert(workOrder);
        }

        serviceRecord.setUnitId(user.getUnitId());
        serviceRecord.setUnitName(user.getUnitName());

        UserServiceOrderVO resultVO = new UserServiceOrderVO();

        List<Sqfw_workorder> workOrderList = sqfwWorkorderService.query(Cnd.where("sqfw_id", "=", serviceRecord.getId()).and("user_id", "=", userId));
        List<SqfwWorkOrderVO> userVOList = sqfwWorkorderService.getVO(workOrderList);
        if (workOrderList.size() > 0) {
            resultVO.setUserWorkOrder(userVOList.get(0));
            Cnd cnd1 = Cnd.NEW();
            cnd1.and(Sqfw_completeflow::getWorkerId, "=", userVOList.get(0).getId());
            Sqfw_completeflow sqfwCompleteflow = sqfwCompleteflowService.fetch(cnd1);
            if (sqfwCompleteflow != null) {
                serviceRecord.setStatus(true);
            }
        }

        // 根据sqfw_id 和 from_userid 查询相应的工单信息
        List<Sqfw_workorder> userWorkOrderList = sqfwWorkorderService.query(Cnd.where("sqfw_id", "=", serviceRecord.getId())
                .and("from_user_id", "=", serviceRecord.getCreatedBy()));
        List<SqfwWorkOrderVO> otherUserVOList = sqfwWorkorderService.getVO(userWorkOrderList);
        resultVO.setUserWorkOrderList(otherUserVOList);
        BeanUtil.copyProperties(serviceRecord, resultVO);
        // 使用id和userId查workOrder
        return Result.success(resultVO);
    }

    @Override
    public void afterInsertForSummary(Sqfw_formSummary_new formSummary) {
        if(StrUtil.isNotEmpty(formSummary.getSqfwId())){
            Sqfw_servicerecord data= this.fetch(formSummary.getSqfwId());
            if(ObjectUtil.isNotEmpty(data)){
                return;
            }
            Sqfw_servicerecord save =new Sqfw_servicerecord();
            save.setId(formSummary.getSqfwId());
            BeanUtil.copyProperties(formSummary,save,"id");
            save.setCreatedBy(SecurityUtil.getUserId());
            save.setUser_id(SecurityUtil.getUserId());
            save.setCreatedAt(System.currentTimeMillis());
            this.insert(save);
        }

    }

    private String generateCondition(Sqfw_servicerecord bean, boolean isAdmin, String userId) {
        String condition = "  ";

        String timeFormat = "yyyy-MM-dd HH:mm:ss";

        if (!isAdmin) {
            condition += " and ( record.createdby = '" + userId + "' OR work_order.user_id = '" + userId + "' ) ";
        }

        if (StringUtils.isNotBlank(bean.getCustomer_name())) {
            condition += " and record.customer_name like '%" + bean.getCustomer_name() + "%' ";
        }
        if (StringUtils.isNotBlank(bean.getCustomer_phone())) {
            condition += " and record.customer_phone like '%" + bean.getCustomer_phone() + "%' ";
        }
        if (StringUtils.isNotBlank(bean.getConnect_obj())) {
            condition += " and record.connect_obj like '%" + bean.getConnect_obj() + "%' ";
        }
        if (StringUtils.isNotBlank(bean.getCustomer_address())) {
            condition += " and record.customer_address like '%" + bean.getCustomer_address() + "%' ";
        }
        if (StringUtils.isNotBlank(bean.getType())) {
            condition += " and record.type = '" + bean.getType() + "'  ";
        }
        if (bean.getConnect_time() != null) {
            DateTime endTime = DateUtil.endOfDay(bean.getConnect_time());
            condition += " and record.connect_time between '" + DateUtil.format(bean.getConnect_time(), timeFormat) + "' AND '" + DateUtil.format(endTime, timeFormat) + "' ";
        }
        if (bean.getEnd_time() != null) {
            DateTime endTime = DateUtil.endOfDay(bean.getEnd_time());
            condition += " and record.connect_time between '" + DateUtil.format(bean.getEnd_time(), timeFormat) + "' AND '" + DateUtil.format(endTime, timeFormat) + "' ";
        }
        if (bean.getDuration() != null) {
            condition += " and record.duration >= '" + bean.getDuration() + "' ";
        }
        if (StringUtils.isNotBlank(bean.getLabel())) {
            condition += " and record.label like '%" + bean.getLabel() + "%' ";
        }
        if (StringUtils.isNotBlank(bean.getCustomer_need())) {
            condition += " and record.customer_need like '%" + bean.getCustomer_need() + "%' ";
        }
        if (StringUtils.isNotBlank(bean.getService_name())) {
            String serviceName = bean.getService_name();
            serviceName = serviceName.replace("，", ",");
            List<String> sysUserNameList = Lists.newArrayList(serviceName.split(","));
            List<Sys_user> sysUserList = sysUserService.query(Cnd.where("username", "in", sysUserNameList));
            Set<String> sysUserIdSet = sysUserList.stream().map(item -> "'" + item.getId() + "'").collect(Collectors.toSet());
            if (sysUserIdSet.size() > 0) {
                condition = " and work_order.to_user_id in ( " + Joiner.on(",").join(sysUserIdSet) + " )";
            }
        }
        if (StringUtils.isNotBlank(bean.getService_phone())) {
            String servicePhone = bean.getService_phone();
            servicePhone = servicePhone.replace("，", ",");
            List<String> sysUserPhoneList = Lists.newArrayList(servicePhone.split(","));
            List<Sys_user> sysUserList = sysUserService.query(Cnd.where("loginname", "in", sysUserPhoneList));
            Set<String> sysUserIdSet = sysUserList.stream().map(item -> "'" + item.getId() + "'").collect(Collectors.toSet());
            if (sysUserIdSet.size() > 0) {
                condition = " and work_order.to_user_id in ( " + Joiner.on(",").join(sysUserIdSet) + " )";
            }
        }
        if (bean.getFinish_time() != null) {
            DateTime endTime = DateUtil.endOfDay(bean.getFinish_time());
            condition += " and work_order.complete_time between '" + DateUtil.format(bean.getFinish_time(), timeFormat) + "' AND '" + DateUtil.format(endTime, timeFormat) + "'";
        }
        if (StringUtils.isNotBlank(bean.getHandle_result())) {
            condition += " and work_order.wk_status = '" + bean.getHandle_result() + "' ";
        }

        return condition;
    }

    public List<JSONObject> getList(Sql sqlExecute) {
        sqlExecute.setCallback((connection, rs, sql) -> {
            List<Map<String, Object>> resultList = Lists.newArrayList();

            while (rs.next()) {
                Map<String, Object> map = Result2Map(rs);
                JSONObject jsonObject = new JSONObject(map);
                resultList.add(jsonObject);
            }
            return resultList;
        });

        dao().execute(sqlExecute);
        return sqlExecute.getList(JSONObject.class);
    }


    public Map<String, Object> Result2Map(ResultSet rs)
            throws SQLException {
        Map<String, Object> hm = new HashMap<>();
        ResultSetMetaData rsmd = rs.getMetaData();
        int count = rsmd.getColumnCount();
        for (int i = 1; i <= count; i++) {
            String key = rsmd.getColumnName(i);
            String value = rs.getString(i);
            hm.put(key, value);
        }
        return hm;
    }
}
